﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using UTSDAL.LINQSQL.Model;
using log4net;
using UTSDAL.LINQSQL.DAO;
using UTSDAL.LINQSQL.Views;
using UTS.Controls;

public partial class pages_admin_reservation_Insert : System.Web.UI.Page
{
    private static readonly ILog log = LogManager.GetLogger(typeof(pages_admin_reservation_Insert));

    private ReservationView selectedTimetableEvent = null;

    private TimetableEventDAO timetableEventDAO = new TimetableEventDAO();

    protected void Page_Load(object sender, EventArgs e)
    {

        // Check if Timetable is being Edited or Added  
        if (Session["selectedReservation"] != null)               // Timetable being edited
        {
            selectedTimetableEvent = (ReservationView)Session["selectedReservation"];

            Reservation_CohortDropDownList.SelectedValue = selectedTimetableEvent.Cohort.CohortId.ToString();            
            Reservation_SemesterDropDownList.SelectedValue = selectedTimetableEvent.Semester.SemesterId.ToString();
            Reservation_ModuleDropDownList.SelectedValue = selectedTimetableEvent.Module.ModuleId.ToString();

            if (!Page.IsPostBack)
            {
                LoadClassEventsForModule(selectedTimetableEvent.Module);
            }
            
        }     
    }

    private List<TimetableEvent> moduleEvents = null;

    private void LoadClassEventsForModule(Module module)
    {
            moduleEvents = timetableEventDAO.findTimetableEventsForModule(module);
            ClassEventRepeater.DataSource = moduleEvents;
            ClassEventRepeater.DataBind();        
    }

    protected void ClassEventRepeater_ItemCreated(object sender, RepeaterItemEventArgs e)
    {

        
        if (moduleEvents != null && moduleEvents.Count > 0)
        {
            TimetableEvent classEvent = moduleEvents.ElementAt(e.Item.ItemIndex);

            if (!TimeUtils.isTimetableEventNew(classEvent))
            {
                CheckBox classEventReservedCheckbox = (CheckBox)e.Item.FindControl("ClassEventReserved");
                classEventReservedCheckbox.Checked = true;
            }

            Literal classEventTypeNameLiteral = (Literal)e.Item.FindControl("ClassEventTypeNameLiteral");
            classEventTypeNameLiteral.Text = classEvent.ModuleEvent.ModuleEventType.ModuleEventTypeName;

            HiddenField classEventTypeID = (HiddenField)e.Item.FindControl("ClassEventTypeId");
            classEventTypeID.Value = classEvent.ModuleEventId.ToString();

            if (!TimeUtils.isTimeSpanNull(classEvent.StartTime))
            {
                TextBox classEventStartTimeTextbox = (TextBox)e.Item.FindControl("ClassEventStartTimeTextbox");
                classEventStartTimeTextbox.Text = TimeUtils.convertTimespan(classEvent.StartTime);
            }

            if (!TimeUtils.isTimeSpanNull(classEvent.EndTime))
            {
                TextBox classEventStopTimeTextbox = (TextBox)e.Item.FindControl("ClassEventStopTimeTextbox");
                classEventStopTimeTextbox.Text = TimeUtils.convertTimespan(classEvent.EndTime);
            }

            
            CourseDayDropDownList courseDayDropDownList = (CourseDayDropDownList)e.Item.FindControl("CourseDayDropDownList");
            courseDayDropDownList.reload();
            

            RoomDropDownList roomDropDownList = (RoomDropDownList)e.Item.FindControl("ClassEventRoomDropDown");
            roomDropDownList.reload();

            log.Debug("Item Created = " + classEventTypeNameLiteral.Text);


        }

    }


    private ModuleDAO moduleDAO = new ModuleDAO();

    protected void Reservation_CohortDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
      
        log.Debug("Reservation_CohortDropDownList_SelectedIndexChanged = " + Reservation_CohortDropDownList.SelectedValue);

        if (StringUtils.isValidGuid(Reservation_CohortDropDownList.SelectedValue))
        {
            Guid selectedCohortId = new Guid(Reservation_CohortDropDownList.SelectedValue);
            Reservation_ModuleDropDownList.DataSource = moduleDAO.findModulesByCohortId(selectedCohortId);
        }
        else
        {
            Reservation_ModuleDropDownList.DataSource = moduleDAO.selectAll();
        }

        // Because Ajax Update Event does not cause a non post back request
        Reservation_ModuleDropDownList.DataBind();
        DropDownUtils.addDefaultLabel(Reservation_ModuleDropDownList, "Select A Module");
                

        ReservationEditingPanel.Update();
    }

    private ModuleEventDAO moduleEventDAO = new ModuleEventDAO();

    protected void Reservation_ModuleDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        log.Debug("Reservation_ModuleDropDownList_SelectedIndexChanged =" + Reservation_ModuleDropDownList.SelectedValue);
        moduleEvents =   timetableEventDAO.findTimetableEventsByModuleId(new Guid(Reservation_ModuleDropDownList.SelectedValue));

        log.Debug("Events found = " + moduleEvents.Count);
        
        ClassEventRepeater.DataSource = moduleEvents;
        ClassEventRepeater.DataBind();
               

        ReservationEditingPanel.Update();
    }

    private TimetableEventTypeDAO timetableEventTypeDao = new TimetableEventTypeDAO();

    protected void SaveReservations(object sender, EventArgs e)
    {
        log.Debug("Save Reservation = "+ClassEventRepeater.Items.Count);

        foreach (RepeaterItem item in ClassEventRepeater.Items)
        {
            CheckBox classEventReserved = (CheckBox)item.FindControl("ClassEventReserved");

            if (classEventReserved.Checked)
            {

                HiddenField classEventId = (HiddenField)item.FindControl("ClassEventId");
                HiddenField classEventTypeId = (HiddenField)item.FindControl("ClassEventTypeId");
                
                TextBox startTime = (TextBox)item.FindControl("ClassEventStartTimeTextbox");
                TextBox endTime = (TextBox)item.FindControl("ClassEventStopTimeTextbox");
                DropDownList courseDay = (DropDownList)item.FindControl("CourseDayDropDownList");
                DropDownList room = (DropDownList)item.FindControl("ClassEventRoomDropDown");

                TimetableEvent timetableEventToUpdate = timetableEventDAO.findById(new Guid(classEventId.Value));

                // checking if is timetableEvent is a new one
                if (timetableEventToUpdate == null)  //adding
                {

                    timetableEventToUpdate = new TimetableEvent();
                    timetableEventToUpdate.Cohort = new CohortDAO().findById(new Guid(Reservation_CohortDropDownList.SelectedValue));
                    timetableEventToUpdate.Semester = new SemesterDAO().findById(new Guid(Reservation_SemesterDropDownList.SelectedValue));

                    timetableEventToUpdate.Module = moduleDAO.findById(new Guid(Reservation_ModuleDropDownList.SelectedValue));

                    log.Debug("Class Event Type Id = " + classEventTypeId.Value);
                    timetableEventToUpdate.ModuleEvent = moduleEventDAO.findById(new Guid(classEventTypeId.Value));
                    
                    log.Debug("Module Event Id = " + timetableEventToUpdate.ModuleEventId);


                    String timeString = TimeUtils.adjustTimeString(startTime.Text.Trim());
                    timetableEventToUpdate.StartTime = TimeSpan.Parse(timeString);
                    timeString = TimeUtils.adjustTimeString(endTime.Text.Trim());
                    timetableEventToUpdate.EndTime = TimeSpan.Parse(timeString);

                    timetableEventToUpdate.CourseDay = new CourseDayDAO().findById(new Guid(courseDay.SelectedItem.Value));
                    timetableEventToUpdate.Room = new RoomDAO().findById(new Guid(room.SelectedItem.Value));
                    timetableEventToUpdate.TimetableEventType = timetableEventTypeDao.getReservationEventType();

                    log.Debug("Timetable Event constructed ");
                    log.Debug("Cohort Id =" + timetableEventToUpdate.CohortId);
                    log.Debug("Semester Id = " + timetableEventToUpdate.SemesterId);
                    log.Debug("Module Id = " + timetableEventToUpdate.ModuleId);
                    log.Debug("ModuleEvent Id = " + timetableEventToUpdate.ModuleEventId);
                    log.Debug("Start Time = " + timetableEventToUpdate.StartTime);
                    log.Debug("End Time = " + timetableEventToUpdate.EndTime);
                    log.Debug("CourseDay Id =" + timetableEventToUpdate.CourseDayId);
                    log.Debug("Room Id = " + timetableEventToUpdate.RoomId);
                    log.Debug("TimetableEventType Id = " + timetableEventToUpdate.TimetableEventTypeId);
                    timetableEventToUpdate.TimetableEventId = Guid.NewGuid();
                    log.Debug("TimetableEventId = " + timetableEventToUpdate.TimetableEventId);
                    
                    timetableEventDAO.insert(timetableEventToUpdate);
                }

            }
        }


    }



}
